# vim: set fileencoding=utf-8 :
#
# (C) 2015,2016 Guido Günther <agx@sigxcpu.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, please see
#    <http://www.gnu.org/licenses/>

import os
import os.path

from tests.component import (ComponentTestBase,
                             ComponentTestGitRepository)
from tests.component.deb import (
        DEB_TEST_DATA_DIR,
        make_source_control_file_path,
        )

from nose.tools import ok_, eq_

from gbp.scripts.import_dsc import main as import_dsc
from gbp.scripts.buildpackage import main as buildpackage


class TestBuildpackage(ComponentTestBase):
    """Test building a debian package"""

    def setUp(self):
        """ Set up test fixtures. """
        super(TestBuildpackage, self).setUp()

    def check_hook_vars(self, name, vars):
        """
        Check that a hook hat the given vars in
        it's environment.
        This assumes the hook was set too
            printenv > hookname.oug
        """
        env = []
        with open('%s.out' % name) as f:
            env = [line.split('=')[0] for line in f.readlines()]

        for var in vars:
            ok_(var in env, "%s not found in %s" % (var, env))

    def import_source_control_file(self, dsc_path):
        """ Import to the repo from the source control file (‘*.dsc’). """
        result = import_dsc(['arg0', dsc_path])
        self.assertEqual(result, 0)

    def buildpackage(self, repo_dir, build_args):
        """ Invoke the command to build the package. """
        os.chdir(repo_dir)
        ret = buildpackage(['arg0'] + build_args)
        ok_(ret == 0, "Building the package failed")

    def check_buildpackage_hook_vars(self):
        """ Check the hook variables for buildpackage. """
        self.check_hook_vars('prebuild', ["GBP_BUILD_DIR",
                                          "GBP_GIT_DIR",
                                          "GBP_GIT_DIR",
                                          "GBP_BUILD_DIR"])

        self.check_hook_vars('postbuild', ["GBP_CHANGES_FILE",
                                           "GBP_BUILD_DIR",
                                           "GBP_CHANGES_FILE",
                                           "GBP_BUILD_DIR"])

    def test_debian_buildpackage(self):
        """Test that building a native debian package works."""
        test_package_name = 'git-buildpackage'
        test_version = '0.4.14'
        dsc_path = make_source_control_file_path(
                'dsc-native', test_package_name, test_version)
        self.import_source_control_file(dsc_path)

        test_repo_dir = os.path.abspath(test_package_name)
        test_repo = ComponentTestGitRepository(test_repo_dir)
        build_args = [
                '--git-prebuild=printenv > prebuild.out',
                '--git-postbuild=printenv > postbuild.out',
                '--git-builder=/bin/true',
                '--git-cleaner=/bin/true']
        self.buildpackage(test_repo_dir, build_args)
        eq_(os.path.exists('prebuild.out'), True)
        self.check_buildpackage_hook_vars()

    def test_non_native_buildpackage(self):
        """Test that building a non-native Debian package works."""
        test_package_name = 'hello-debhelper'
        test_version = '2.8-1'
        dsc_path = make_source_control_file_path(
                'dsc-3.0', test_package_name, test_version)
        self.import_source_control_file(dsc_path)

        test_repo_dir = os.path.abspath(test_package_name)
        test_repo = ComponentTestGitRepository(test_repo_dir)
        build_args = [
                '--git-prebuild=printenv > prebuild.out',
                '--git-postbuild=printenv > postbuild.out',
                '--git-builder=/bin/true',
                '--git-cleaner=/bin/true']
        self.buildpackage(test_repo_dir, build_args)
        eq_(os.path.exists('prebuild.out'), True)
        self.check_buildpackage_hook_vars()

    def test_tag_only(self):
        """Test that only tagging a native Debian package works."""
        test_package_name = 'git-buildpackage'
        test_version = '0.4.14'
        dsc_path = make_source_control_file_path(
                'dsc-native', test_package_name, test_version)
        self.import_source_control_file(dsc_path)

        test_repo_dir = os.path.abspath(test_package_name)
        test_repo = ComponentTestGitRepository(test_repo_dir)

        tag_name = 'debian/{version}'.format(version=test_version)
        # Make sure we can tag again.
        test_repo.delete_tag(tag_name)
        build_args = [
                '--git-tag-only',
                '--git-posttag=printenv > posttag.out',
                '--git-builder=touch builder-run.stamp',
                '--git-cleaner=/bin/true']
        self.buildpackage(test_repo_dir, build_args)
        eq_(os.path.exists('posttag.out'), True)
        eq_(os.path.exists('builder-run.stamp'), False)
        self.check_hook_vars('posttag', ["GBP_TAG",
                                         "GBP_BRANCH",
                                         "GBP_SHA1"])
